package com.example.keike.downloadmaster.download;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.example.keike.downloadmaster.SelfApplication;
import java.io.File;

/**
 * 暂时无法监控到通知栏取消按钮的点击广播
 * <p>
 * <p>
 * <p>
 * Created by ketan on 2017/5/26.
 */
public class DownloadTask extends Thread {

    public final static int PROCESS = 0x1122;
    private long mLoadId = -1;
    private String mUrl;
    private Handler mHandler;
    private String mLoadName;
    private Context mContext;
    private DownloadUtil mLoadMgr;
    private DownloadReceiver mReceiver;
    private final String DEF_APP_NAME = "download.apk";
    private final String AUTHORITY_PATH = "com.example.keike.downloadmaster.fileprovider";

    public DownloadTask(String url, String loadTitle, Handler handler, boolean force) {
        Log.e("","--------6");

        mUrl = url;
        mLoadName = loadTitle;
        this.mHandler = handler;
        this.mContext = SelfApplication.getContext();
        this.mLoadMgr = DownloadUtil.create(mContext);
        registerReceiver();


    }
    @Override
    public void run() {
        String fileName = mLoadMgr.getFileName(DEF_APP_NAME, mUrl);
        CursorBean historyBean = mLoadMgr.queryProcess(fileName);
        if (historyBean != null && historyBean.getId() != -1) {//证明有下载的线程
            int status = historyBean.getStatus();
            switch (status) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    long timeDiff = System.currentTimeMillis() - historyBean.getTimeStamp();
                    double hour = (timeDiff) / 1000D / 60D / 60D;//时效是一个小时
                    boolean exists = new File(historyBean.getFile()).exists();
                    if (hour <= 1 && timeDiff > 0 && exists) {
                        if (mHandler != null) {
                            Message msg = Message.obtain();
                            msg.what = PROCESS;
                            msg.obj = new Integer(100);
                            mHandler.sendMessage(msg);
                        }
                        mLoadMgr.install(historyBean.getFile(), AUTHORITY_PATH);
                    } else {
                        mLoadId = mLoadMgr.reload(mLoadId, mLoadName, DEF_APP_NAME, mUrl);
                    }
                    break;
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                case DownloadManager.STATUS_PAUSED:
                    mLoadId = historyBean.getId();
                    break;
                default:
                    mLoadId = mLoadMgr.reload(mLoadId, mLoadName, DEF_APP_NAME, mUrl);
                    break;
            }

        } else {
            mLoadId = mLoadMgr.reload(mLoadId, mLoadName, DEF_APP_NAME, mUrl);
        }
    }


    private void registerReceiver() {
        Log.e("","--------7");

        this.mReceiver = new DownloadReceiver();
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        mContext.registerReceiver(this.mReceiver, intentFilter);
        //下载进度更新
        mContext.getContentResolver().registerContentObserver(
                Uri.parse("content://downloads/"), true,
                contentObserver);
    }

    public void removeReceiver() {
        try {
            if (mContext != null && contentObserver != null) {
                mContext.getContentResolver().unregisterContentObserver(contentObserver);
            }
            if (mContext != null && mReceiver != null) {
                mContext.unregisterReceiver(mReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void destroyTask() {
        if (mLoadId != -1) {
            mLoadMgr.getDownloadMgr().remove(mLoadId);
        }
        try {
            mContext.getContentResolver().unregisterContentObserver(contentObserver);
            mContext.unregisterReceiver(mReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final ContentObserver contentObserver = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if (mLoadId == -1) return;
            Cursor cursor = mLoadMgr.getCursor(false, mLoadId);
            while (cursor.moveToNext()) {
                int mDownload_so_far = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int mDownload_all = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                int mProgress = (mDownload_so_far * 100) / mDownload_all;
                if (mHandler != null) {
                    Message msg = Message.obtain();
                    msg.what = PROCESS;
                    msg.obj = new Integer(mProgress);
                    mHandler.sendMessage(msg);
                }
            }
        }
    };

    private class DownloadReceiver extends BroadcastReceiver {
        public void onReceive(final Context context, final Intent intent) {

            if (intent.getAction() == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (reference != -1 && reference == mLoadId) {
                    Cursor cursor = mLoadMgr.getCursor(false, (int) reference);
                    try {
                        if (cursor != null && cursor.moveToFirst()) {
                            String filePath = mLoadMgr.getDownloadFile(cursor);
                            if (!TextUtils.isEmpty(filePath)) {
                                mLoadMgr.install(filePath, AUTHORITY_PATH);
                                removeReceiver();
                            }
                        }
                        cursor.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        try {
                            if (null != cursor) {
                                cursor.close();
                                removeReceiver();
                            }
                        } catch (Exception ex) {
                        }
                    }
                }
            }
        }
    }
}